package com.rjj.wlqq.simditor;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 富文本编辑器使用
 */
@Controller
public class SimditorController {
    private static Logger log = LoggerFactory.getLogger(SimditorController.class);

    @RequestMapping("/simditor")
    public String simditor() {
        return "simditor/simditor";
    }


    @RequestMapping("/simditor2")
    public String simditor2() {
        return "simditor/自己写的demo";
    }


    /**
     * 表单提交
     * 富文本编辑器提交会提交所有的内容，保存就行，显示的时候我们直接拿出来放到页面上就可以了
     */
    @RequestMapping("/save")
    @ResponseBody
    public String save(HttpServletRequest request, HttpServletResponse response){
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((k, v) ->{
           log.info("k:{}" , k);
            for (String s : v) {
               log.info("v:{}", s);
            }
        });
       log.info(request.getParameter("name"));
        return "ok";
    }

    /**
     * 本地图片上传
     * /activity/imageUpload
     */
    @RequestMapping("/imageUpload")
    @ResponseBody
    public JSONObject imageUpload(@RequestParam("imageName") MultipartFile file, HttpServletRequest request) {
        String queryString = request.getQueryString();
        JSONObject json = new JSONObject();
        boolean flag = false;
        String msg = "上传失败";
        String originalFilename = file.getOriginalFilename();
        //如果保存文件就把文件输出到指定的目录下就可以了
        /*
        <pre>
        file.transferTo(dest);
         dest的目录表需要绝对路径，相对路径会出现找不到文件的问题
         运行在保存文件 file.transferTo(dest) 报错
        问题
        dest 是相对路径，指向 upload/doc20170816162034_001.jpg
        file.transferTo 方法调用时，判断如果是相对路径，则使用temp目录，为父目录
        因此，实际保存位置为 "C:/Users/xxxx/AppData/Local/Temp/tomcat.372873030384525225.8080/work/Tomcat/localhost/ROOT/upload/doc20170816162034_001.jpg"

        一则，位置不对，二则没有父目录存在，因此产生上述错误。
        </pre>
         */
        String filePath = null;
        try {
            //上传文件到的路径是绝对路径，/F:/eclipse2/workspace/demo/target/classes//static/img\
            filePath = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath() + "/static/img" + File.separator;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        long time = System.currentTimeMillis();
        String endTag = time + originalFilename.substring(originalFilename.indexOf("."));
        File dest = new File(new File(filePath).getAbsolutePath() + File.separator + endTag);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
            //uploadFile(file.getBytes(),filePath , originalFilename);
            msg = "上传成功";
            flag = true;
            log.info("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传失败");
        } catch (Exception e) {
            e.printStackTrace();
        }

        json.put("success", flag);
        json.put("msg", msg);
        //保存上传图片的路径
        json.put("file_path", "/img" + File.separator + endTag);
        return json;
    }


    /**
     * 把文件写道输出流中
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {

        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
